<template>
  <div class="test-custom-content-2">
    <label>再次輸入資料</label>
    <input v-bind="input" type="text" />
    <div v-if="errors?.input" class="error-msg">{{ errors.input }}</div>
  </div>
</template>

<script setup>
import { toTypedSchema } from '@vee-validate/yup'
import { useForm } from 'vee-validate'
import * as yup from 'yup'
import { ref } from 'vue'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { useConfirmData } from '@/compositions/dialog/confirm-data'

const v = ref('')
const errMsg = ref('')

const { getPrevInputData } = usePopupDialogStore()

useConfirmData(validator)

function validator() {
  const prevData = getPrevInputData()

  // 驗證資料沒通過回傳 fasle
  if (v.value === '') {
    errMsg.value = '不能為空哦呵呵'
    return false
  }

  if (prevData && v.value !== prevData.input) {
    errMsg.value = '輸入資料不一致'
    return false
  }

  // 驗證資料通過打包成想回傳的樣子回傳
  const data = { input: v.value }

  // 重置資料內容
  reset()

  return data
}

function reset() {
  v.value = ''
  errMsg.value = ''
}

/**
 * vee-validate & yup 驗證
 *
 */

// 設定語系資料
yup.setLocale({
  mixed: {
    required: () => `這是必填欄位喔`,
  },
  string: {
    min: ({ min }) => `最少要輸入${min}個字喔`,
    max: ({ max }) => `最多可以輸入${max}個字喔`,
    matches: `不可以有標點符號喔`,
    email: `這不是正確的信箱格式喔`,
  },
})

// 設定驗證規則
const schema = toTypedSchema(
  yup.object({
    input: yup
      .string()
      .required()
      .min(5)
      .max(10)
      .matches(/^[a-zA-Z0-9]+$/),
  }),
)

// 設定 vee-validate hook
const { values, errors, defineInputBinds, handleSubmit } = useForm({
  validationSchema: schema,
})

const input = defineInputBinds('input', {
  validateOnInput: false,
  validateOnBlur: false,
  validateOnChange: true,
})

const onSubmit = handleSubmit((values) => {
  console.log(values)
})
</script>

<style lang="scss" scoped>
.test-custom-content-2 {
  input {
    width: 100%;
    padding: 0.5rem;
    margin: 0.5rem 0;
    border: 1px solid #e0e0e0;
  }

  .error-msg {
    color: red;
  }
}
</style>
